package com.zjsru.studyplan1;

/**
 * 二分查找
 */
public class search {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length;
        int mid = (left + right) / 2;
        if (nums.length == 1) {
            if (nums[nums.length - 1] == target) return right - 1;
            else return -1;
        }

        for (int i = 0; i <= right; i++) {
            if (target > nums[mid]) {
                mid = mid + 1;
                if (mid >= right) break;
            } else if (target < nums[mid]) {
                left = left + 1;
                mid = mid - 1;
                if (mid < 0) break;
            } else if (target == nums[mid]) {
                return mid;
            }
        }
        return -1;



//        int low = 0;
//        int high = nums.length - 1;
//        while (low <= high) {
//            int mid = (high - low) / 2 + low;
//            if (target == nums[mid]) {
//                return mid;
//            } else if (target < nums[mid]) {
//                high = mid - 1;
//            } else {
//                low = mid + 1;
//            }
//        }
//        return -1;
    }

    public static void main(String[] args) {
        int[] nums = new int[]{1,3,5,6};
        int target = 7;
        search search = new search();
        int result = search.search(nums, target);
        System.out.println(result);
    }

}
// 搜素插入位置
//    int left = 0;
//    int right = nums.length-1;
//    int tip = right+1;
//        while(left <= right){
//                int mid = (right - left)/2 + left;
//                if(nums[mid] >= target){
//                tip =mid;
//                right = mid -1;
//                }else{
//                left = mid +1;
//                }
//                }
//                return tip;